package com.dycong.common.leetcode.yi;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yilin
 * Date: 2019-09-09
 * Time: 17:10
 */
public class Intersect {

    public static void main(String[] args) {
        Arrays.stream(intersect(new int[]{4, 9, 5}, new int[]{9, 4, 9, 8, 4})).forEach(item -> System.out.println(item));
    }

    public static int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> masp = new HashMap<>();
        for (Integer item : nums1) {
            masp.put(item, masp.getOrDefault(item, 0) + 1);
        }
        //再遍历第二个数组，将于map中找到的key放入list中
        LinkedList<Integer> list = new LinkedList<Integer>();

        for (Integer item : nums2) {
            Integer result = masp.getOrDefault(item, 0);
            if (result > 0) {
                list.add(item);
                masp.put(item, result - 1);
            }
        }
        //最后，将list中的值放入数组中
        int count = list.size();
        int[] aux = new int[count];
        for (int i = 0; i < count; i++) {
            aux[i] = list.poll();
        }

        return aux;
    }
}
